import Data from '@/utils/data.js';

class websocket {
    constructor() {
        this.url = Data.wsAddr;                  // WebSocket 服务器地址 
        this.uid = null;
		this.token=null;
        this.heartBeatInterval = 15000; // 心跳间隔时间，默认 15 秒
        this.reconnectInterval = 5000; // 重连间隔时间，默认 5 秒
        this.maxReconnectAttempts = 50; // 最大重连次数
        this.reconnectAttempts = 0;              // 当前重连次数
        this.heartBeatTimeoutId = null;          // 心跳定时器ID
        this.reconnectTimeoutId = null;          // 重连定时器ID
        this.isConnected = false;                // WebSocket 是否已连接
        this.messageQueue = [];                  // 消息队列
        this.socketTask = null;                  // WebSocket 任务
        this.isManuallyClosed = false;           // 标志，指示连接是否被手动关闭
		this.store=null;
    }

    // 初始化 WebSocket
    connect(uid,token) {
        this.uid = uid;
		this.token=token;
        if (!this.url) {
            console.error('WebSocket URL 未提供');
            return;
        }
        // 创建 WebSocket 连接
        this.socketTask = uni.connectSocket({
            url: this.url +"/"+this.uid+"/"+this.token,
            success: () => {
			 // uni.showToast({ title: '已连接服务器', icon: 'none', duration: 1500 });
            },
            fail: (error) => {
                // console.error('WebSocket 连接请求发送失败', error);
                this.reconnect();
            }
        });

        // 监听连接打开事件
        this.socketTask.onOpen(() => {
            // console.log('WebSocket 已打开');
			// uni.showToast({
			// 	title:"尽情浏览吧！",
			// 	icon:"success",
			// 	duration:500
			// })
            this.isConnected = true;
			console.log('WebSocket 连接');
			this.store.commit('changeConnect', true);
			uni.setStorageSync('isConnect',true)
            this.reconnectAttempts = 0;
            this.startHeartBeat();
            this.flushMessageQueue();
        });

        // 监听连接关闭事件
        this.socketTask.onClose(() => {
            // console.log('WebSocket 已关闭');
            this.isConnected = false;
            this.stopHeartBeat();
            this.store.commit('changeConnect', false);
			uni.setStorageSync('isConnect',false)
            // 仅在未手动关闭的情况下重连
            if (!this.isManuallyClosed) {
                this.reconnect();
            } else {
                console.log('主动关闭websocket，停止重连');
            }
        });

        // 监听连接错误事件
        this.socketTask.onError((error) => {
            console.error('WebSocket 发生错误');
			// uni.showToast({
			// 	title:"服务器连接失败",
			// 	icon:"error",
			// 	duration:700
			// })
			this.store.commit('changeConnect', false);
			uni.setStorageSync('isConnect',false)
            console.log(error);
            this.isConnected = false;
            this.stopHeartBeat();
            this.reconnect();
        });

        // 监听收到消息事件
        this.socketTask.onMessage((data) => {
            console.log('收到 WebSocket 消息，即将处理', data.data);
			var message=JSON.parse(data.data);
            this.handleMessage(message);
        });
    }
    // 处理接收到的消息
       handleMessage(message) {
           // 这里可以根据业务逻辑处理接收到的消息
			//收到消息后，获取发送用户名
			var username;
			if(message.code==2){//账号退出通知
			// #ifdef APP-PLUS
			plus.device.vibrate(1000);
			// #endif
				uni.showToast({ title: message.msg, icon: 'none', duration: 2000 });
				this.close();
				uni.removeStorageSync('UID');
				uni.removeStorageSync('token')
				setTimeout(()=>uni.reLaunch({
						url:"/pages/index/index"
					}),2001)
				return;
			}
			if(message.code==1){
				uni.request({
					url:Data.httpAddr+"/getUsername",
					method:"POST",
					data:{
						data:{
							userId:message.data.senderId
						},
						msgType:'getUsername'
					},
					header: {
						'Content-Type': 'application/json',// 如果需要以JSON格式发送数据
						'token':this.token,
						'uid':this.uid
					},
					success: (res) => {
						if(res.data.code==1){
							username=res.data.data.username
								var usersList = uni.getStorageSync('usersList') || [];
								var userIndex = usersList.findIndex(existingUser =>( existingUser.uid == message.data.senderId)&&(existingUser.toUid==message.data.receiverId));
								if (userIndex !== -1) { // 如果发消息的人已经在本地有记录了
								    // 更新用户信息
								    usersList[userIndex].content = message.data.content;
								    usersList[userIndex].time = message.data.createdAt;
								    usersList[userIndex].hasNew = true;
								
								    // 将用户移到最前面
								    var user = usersList.splice(userIndex, 1)[0]; // 删除用户并获取该用户
								    usersList.unshift(user); // 将用户添加到最前面
								} else {
								    var newUser = {
								        uid: message.data.senderId,
										toUid:message.data.receiverId,
								        avatar: '',
								        username,
								        time: message.data.createdAt,
								        content: message.data.content,
								        offsetX: 0,
								        isTop: false,
								        hasNew: true,
								        isDeleting: false,
								    };
								    // 使用 unshift 将 newUser 插入到最前面
								    usersList.unshift(newUser);
								}
								
								var allMessagesList = uni.getStorageSync('messagesList') || [];
								var newMessage = {
								    senderId: message.data.senderId,
								    receiverId: message.data.receiverId,
								    content: message.data.content,
								    timestamp: message.data.createdAt,
								    animation: '',
								};
								allMessagesList.push(newMessage);
								uni.setStorageSync('messagesList', allMessagesList);
								uni.setStorageSync('usersList', usersList);
								this.store.commit('changeUsersList', usersList);
								this.store.commit('changeMessagesList', allMessagesList);
				
								// #ifdef APP-PLUS
									plus.device.vibrate(250);
								// #endif
								uni.showToast({ title:username+" 发来消息："+message.data.content, icon: 'none', duration: 1500 });
								if (uni.getSystemInfoSync().platform == "android") {
									let content = username+" 私信你说："+message.data.content;
									let options = {
										"cover" : false,
										"when" : new Date(),
										'title' : "LINK 通知"
									};
									let body = {
										'senderId' :message.data.senderId,
										"username":username,
										"type":1
									}
									let payload = JSON.stringify(body);
									// #ifdef APP
									plus.push.createMessage(content, payload, options);
									// #endif
								}
						}
					}
				})
			}
			if(message.code==4){//新增粉丝
				uni.showToast({
					// title:"用户 "+message.data.sender+" 在 "+message.data.time+"通过 "+message.data.way+" 关注了你",
					title:"恭喜，新增粉丝，快去看看吧！",
					icon:"none",
					duration:1000
				})
				
				var fansList=uni.getStorageSync('fansList')||[]
				const index = fansList.findIndex(fan => fan.senderId === message.data.senderId);
				
				if (index !== -1) {
				    // 如果存在，替换原来的元素
				    fansList[index] = message.data;
				} else {
				    // 如果不存在，插入到开头
				    fansList.unshift(message.data);
				}
				uni.setStorageSync('fansList', fansList);
				this.store.commit("changeFans", fansList);
				// #ifdef APP-PLUS
				plus.device.vibrate(500);
				// #endif
			}else if(message.code==5){//点赞通知
				uni.showToast({
					// title:"用户 "+message.data.sender+" 在 "+message.data.time+" 点赞了你的动态 "+message.data.title,
					title:"有人给你点赞了，快去看看吧！",
					icon:"none",
					duration:1000
				})
				
				var likesList = uni.getStorageSync('likesList') || [];
				
				// 更新 message.data.msg
				message.data.msg = message.msg;
				
				// 查找是否存在相同的元素
				const index = likesList.findIndex(item => 
				    item.way === message.data.way &&
				    item.msg === message.data.msg &&
				    item.title === message.data.title
				);
				
				if (index !== -1) {
				    // 如果存在，替换原来的元素
				    likesList[index] = message.data;
				
				    // 将替换后的元素移到数组的开头
				    const [movedItem] = likesList.splice(index, 1); // 删除该元素
				    likesList.unshift(movedItem); // 插入到开头
				} else {
				    // 如果不存在，插入到开头
				    likesList.unshift(message.data);
				}
				
				console.log(likesList);
				uni.setStorageSync('likesList', likesList);
				this.store.commit("changeLikes", likesList);


				
				
				uni.setStorageSync('likesList',likesList)
				this.store.commit("changeLikes",likesList)
			// #ifdef APP-PLUS
			plus.device.vibrate(300);
			// #endif
			}else if(message.code==6){//评论通知
				uni.showToast({
					// title:"用户 "+message.data.sender+" 在 "+message.data.time+" 评论了你的帖子 "+message.data.title+" "+message.data.comment,
					title:"有人给你评论了，快去看看吧！",
					icon:"none",
					duration:1000
				})
				
				var commentsList=uni.getStorageSync('commentsList')||[]
				message.data.code=message.code
				message.data.msg=message.msg
				commentsList.unshift(message.data)
				console.log(commentsList)
				uni.setStorageSync('commentsList',commentsList)
				this.store.commit("changeComments",commentsList)
				// #ifdef APP-PLUS
				plus.device.vibrate(300);
				// #endif
			}else if(message.code==7){//回复通知
				uni.showToast({
					// title:"用户 "+message.data.sender+" 在 "+message.data.time+" 回复了你 "+message.data.myComment+" "+message.data.otherComment,
					title:"有人给你回复了，快去看看吧！",
					icon:"none",
					duration:1000
				})
				
				var commentsList=uni.getStorageSync('commentsList')||[]
				message.data.code=message.code
				message.data.msg=message.msg
				commentsList.unshift(message.data)
				console.log(commentsList)
				uni.setStorageSync('commentsList',commentsList)
				this.store.commit("changeComments",commentsList)
				// #ifdef APP-PLUS
				plus.device.vibrate(300);
				// #endif
			}
			
			
		}
    // 发送消息
    sendChatMessage(message) {
        var res = false;
        if (this.isConnected) {
            this.socketTask.send({
                data: JSON.stringify({
					code:1,
					msg:"这是聊天消息",
					data:message
				}),
                success: () => {
                    res = true;
                },
                fail: (error) => {
                    console.error('消息发送失败', error);
                    this.messageQueue.push(message); // 发送失败时将消息加入队列
                }
            });
        } else {
            this.messageQueue.push(message); // 连接未建立时将消息加入队列
        }
        return res;
    }
	sendHeartMessage() {
	    var res = false;
	    if (this.isConnected) {
	        this.socketTask.send({
	            data: JSON.stringify({
					code:0,
					msg:"这是心跳消息",
				}),
	            success: () => {
	                res = true;
	            },
	            fail: (error) => {
	                console.error('消息发送失败', error);
	                this.messageQueue.push(message); // 发送失败时将消息加入队列
	            }
	        });
	    } else {
	        this.messageQueue.push(message); // 连接未建立时将消息加入队列
	    }
	    return res;
	}
    // 刷新消息队列
    flushMessageQueue() {
        while (this.messageQueue.length > 0 && this.isConnected) {
            const message = this.messageQueue.shift();
            this.sendMessage(message);
        }
    }

    // 开始心跳检测
    startHeartBeat() {
        this.heartBeatTimeoutId = setInterval(() => {
            if (this.isConnected) {
                this.sendHeartMessage();
            }
        }, this.heartBeatInterval);
    }

    // 停止心跳检测
    stopHeartBeat() {
        if (this.heartBeatTimeoutId) {
            clearInterval(this.heartBeatTimeoutId);
            this.heartBeatTimeoutId = null;
        }
    }

    // 重连机制
    reconnect() {
        if (this.reconnectAttempts >= this.maxReconnectAttempts) {
            console.error('已达到最大重连次数，停止重连');
            return;
        }

        this.reconnectTimeoutId = setTimeout(() => {
            this.reconnectAttempts++;
            this.connect(this.uid,this.token);
        }, this.reconnectInterval);
    }

    // 关闭 WebSocket 连接
    close() {
        this.isManuallyClosed = true; // 设置为手动关闭
        if (this.socketTask) {
            this.socketTask.close({
                success: () => {
                    console.log('WebSocket 已手动关闭');
                    this.isConnected = false;
                    this.stopHeartBeat();
                    clearTimeout(this.reconnectTimeoutId); // 停止重连
                },
                fail: (error) => {
                    console.error('WebSocket 关闭失败', error);
                }
            });
        }
    }
}

export default websocket;
